﻿using System.Collections.Generic;
using System.Linq;
using MMSWebsite.Models;

namespace MMSWebsite.DataAccessManagement
{
    public class RoleAccessProvider
    {
        readonly MMSEntities _entities = new MMSEntities();

        public List<MMS_ROLE> GetAllRoles()
        {
            return _entities.MMS_ROLEs.OrderBy(x => x.RoleName).ToList();
        }

        public List<string> GetAllRoleName()
        {
            return _entities.MMS_ROLEs.OrderBy(x => x.RoleName).Select(r => r.RoleName).ToList();
        }

        public MMS_ROLE GetRoleById(int id)
        {
            return _entities.MMS_ROLEs.Single(r => r.Id == id);
        }

        public void RemoveRole(int id)
        {
            _entities.MMS_ROLEs.DeleteObject(_entities.MMS_ROLEs.Single(r => r.Id == id));
            _entities.SaveChanges();
        }

        public void AddRole(MMS_ROLE role)
        {
            _entities.AddToMMS_ROLEs(role);
            _entities.SaveChanges();
        }

        public void UpdateRole(MMS_ROLE role)
        {
            var updaterole = _entities.MMS_ROLEs.Single(r => r.Id == role.Id);
            updaterole.RoleName = role.RoleName;
            updaterole.Description = role.Description;
            _entities.SaveChanges();
        }

        public bool CheckRoleExist(string rolename, bool editView)
        {
            var roles = GetAllRoles();
            if(editView)
                roles.Remove(roles.FirstOrDefault(r => r.RoleName == rolename));
            return roles.Any(@role => @role.RoleName == rolename);
        }
    }
}